<?php

namespace App\Model\Auth;


use EasySwoole\Component\Di;
use EasySwoole\Redis\Redis;
use EasySwoole\RedisPool\RedisPool;

/**
 * 菜单管理
 * Class MenuModel
 * @package App\Model\Auth
 */
class MenuModel extends \App\Core\BaseModel{

    protected $tableName = 'ss_menu';

    const TYPE_VIEW   = 1;
    const TYPE_BUTTON = 2;

    const MENU_TYPE_INSIDE   = 1;//内部菜单
    const MENU_TYPE_OUTSIDE  = 2;//外部菜单

    protected $casts = [
        'id'             => 'integer',
        'pid'            => 'integer',
        'title'          => 'string',
        'identification' => 'string',
        'type'           => 'integer',
        'sort'           => 'integer',
        'state'          => 'integer',
        'icon'           => 'string',
    ];

    public static function getTypeDict($key = null){
        return self::getMap([
            self::TYPE_VIEW   => '页面',
            self::TYPE_BUTTON => '按钮操作',
        ], $key);
    }

    public static function getMenuTypeDict($key = null){
        return self::getMap([
            self::MENU_TYPE_INSIDE  => '内部菜单',
            self::MENU_TYPE_OUTSIDE => '外部菜单',
        ], $key);
    }

    public function parent(){
        return $this->hasOne(self::class, function($query){
            $query->where('is_delete', 0);
            $query->fields(['id','pid','title','identification','type','sort','state','icon']);
            return $query;
        }, 'pid', 'id');
    }

    /**
     * 获取菜单列表
     * @return array|bool|\EasySwoole\ORM\Collection\Collection|\EasySwoole\ORM\Db\Cursor|\EasySwoole\ORM\Db\CursorInterface
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getLists(){
        $model = self::makeQueryModel(['state'=>self::ENABLED]);

        $model->field(['id','pid','title','identification','type','sort','state','icon','web_path','menu_type']);

        $model->order('sort','desc');

        $list = $model->all();

        return $list->isEmpty() ? [] : $list->toRawArray();
    }

    protected static function onAfterUpdate($model, $res)
    {
        self::delCache('userInfoAuth:');
    }

    protected static function onAfterInsert($model, $res)
    {
        self::delCache('userInfoAuth:');
    }
}
